package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import com.example.myapplication.broadcast.MyBroadcastReceiver;
import com.example.myapplication.net.OkHttpUtil;
import com.example.myapplication.thread.ThreadPoolSum;
import com.example.myapplication.util.HttpClientUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;


public class NetActivity extends AppCompatActivity {

    private TextView textview;
    private String html;
    private final Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net);
        textview = findViewById(R.id.textView1);
        //new MyThread().start();
        findViewById(R.id.button__get).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNetRes();
            }
        });
        findViewById(R.id.button__post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postNetRes();
            }
        });
        findViewById(R.id.getNetRes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get();
            }
        });

    }

    /**
     * handler的post发送消息
     */
    protected void get() {
        ThreadPoolSum threadPoolSum = new ThreadPoolSum();
        ExecutorService executor = threadPoolSum.init();
        // 线程池创建线程submit
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    html = HttpClientUtils.getHtml("https://blog.csdn.net/hfuuhgcc/article/details/84086263?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-84086263-blog-72911382.pc_relevant_multi_platform_whitelistv1_exp2&spm=1001.2101.3001.4242.1&utm_relevant_index=3");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message message = Message.obtain();
                message.what = 1;
                handler.sendMessage(message);
                handler.postDelayed(mUpdateResults,0); //高速UI线程可以更新结果了,延时3s
            }
        });
        // 线程池创建线程execute
        /*executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    html = HttpClientUtils.getHtml("http://10.0.2.2:8082/student/list");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.postDelayed(mUpdateResults,0); //高速UI线程可以更新结果了,延时3s
            }
        });*/
        // 一般线程
        /*new Thread(()->{
            try {
                html = HttpClientUtils.getHtml("https://blog.csdn.net/hfuuhgcc/article/details/84086263?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-84086263-blog-72911382.pc_relevant_multi_platform_whitelistv1_exp2&spm=1001.2101.3001.4242.1&utm_relevant_index=3");
            } catch (Exception e) {
                e.printStackTrace();
            }
            handler.postDelayed(mUpdateResults,1000*3); //高速UI线程可以更新结果了,延时3s
        }).start();*/
    }

    /**
     * handler的post发送消息
     */
    protected void postNetRes() {
        Thread t = new Thread() {
            public void run() {
                try {
                    //要传递的参数
                    List<NameValuePair> postParams = new ArrayList<>();
                    postParams.add(new BasicNameValuePair("page", "1"));
                    postParams.add(new BasicNameValuePair("rows", "1"));
                    //html = HttpClientUtils.useHttpUrlConnectionPost("http://10.0.2.2:8082/student/pagelist",postParams); // post请求
                    html = OkHttpUtil.postUrl("http://10.0.2.2:8082/student/pagelist"); // post请求
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.postDelayed(mUpdateResults,0); //高速UI线程可以更新结果了,延时3s
            }
        };
        t.start();
    }

    /**
     * 获取网页的源码
     */
    protected void getNetRes() {
        Thread t = new Thread() {
            public void run() {
                try {
                    //html = HttpClientUtils.getHtml("https://v1.hitokoto.cn/?c=f&encode=text"); // 获取网页源码 get请求
                    html = HttpClientUtils.useHttpUrlConnectionGet("http://10.0.2.2:8082/student/list"); //get请求
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //高速UI线程可以更新结果了
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textview.setText(html);
                    }
                },0);
            }
        };
        t.start();
    }

    /**
     * 子线程
     */
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            textview.setText(html);
        }
    };


    /**
     * 注册应用内广播接收器
     */
    public void localBroadcast(List<? extends Map<String,?>> data){
        //步骤1：实例化BroadcastReceiver子类 & IntentFilter myBroadcastReceiver
        MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //步骤2：实例化LocalBroadcastManager的实例
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        //步骤3：设置接收广播的类型
        intentFilter.addAction("com.example.myapplication.MY_BROADCAST");
        //步骤4：调用LocalBroadcastManager单一实例的registerReceiver（）方法进行动态注册
        localBroadcastManager.registerReceiver(myBroadcastReceiver, intentFilter);
        //取消注册应用内广播接收器
        //localBroadcastManager.unregisterReceiver(myBroadcastReceiver);
        //发送应用内广播
        Intent intent = new Intent();
        intent.setAction("com.example.myapplication.MY_BROADCAST");
        localBroadcastManager.sendBroadcast(intent);
    }

}